package org.ifdb.service.impl;

import org.ifdb.model.UploadItem;
import org.ifdb.persistency.entity.City;
import org.ifdb.persistency.entity.Country;
import org.ifdb.persistency.entity.State;
import org.ifdb.service.UploadService;
import org.springframework.stereotype.Service;



@Service
public class UploadServiceImpl implements UploadService {
    

	@Override
	public void loadData(UploadItem upload) {
		String[] rows = new String(upload.getFile().getBytes()).split("\n");
           
   		for (int i = 0; i<rows.length;i++){
   			mapAction(rows[i], upload.getName());
   		}	            
		
	}
	
	protected void mapAction(String line, String action) {		
		
		String[] values = line.split(",");
		String cityName = "";
		String stateName = "";
		String countryName = "";
		
		cityName = cleanInvalidData(values[2]);		
		stateName = cleanInvalidData(values[1]);
		countryName = cleanInvalidData(values[0]);				
		
		this.prepareInformation(cityName, stateName, countryName);
	
	
	}
	
	protected Country prepareInformation(String cityName, String stateName, String  countryName){
		
	    if (cityName.length() <= 2 || stateName.length() == 0 || countryName.length() == 0)
	        return null;
	    
	    Country country = null;
	    
	    if (Country.exists(countryName))
	            country = Country.getCountryByName(countryName);
	    else {
	        country = new Country();
	        country.setName(countryName);
	    }
	    State state = country.getStateByName(stateName);
	    
	    if (state == null){
	        state = new State();
	        state.setName(stateName);
	        country.addState(state);
	    } 
	    
	    City city = state.getCityByName(cityName);
	    if (city == null){
	        city = new City();
	        city.setName(cityName);
	        state.addCity(city);
	        
//	        PMF.get().getPersistenceManager().makePersistent(country);
	    } 
	      
		
		return country;
	}
	
	protected String cleanInvalidData(String value){
		value = value.replaceAll("\\r", "");
		return value;
	}

 

}
